package com.phantom.nio.c1;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

@Slf4j
public class TestByteBuffer {

    public static void main(String[] args) {

        try (FileChannel channel = new FileInputStream("data.txt").getChannel()) {
            // 准备缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(10);

            while (true) {
                int len = channel.read(buffer);  // 从channel读，向buffer写
                log.debug("读取到的字节数 {}", len);
                if (len == -1) {
                    break;
                }
                buffer.flip(); // 切换至读模式
                while (buffer.hasRemaining()) {
                    byte b = buffer.get();
                    log.debug("读取到的字节 {}", (char) b);
                }

                buffer.clear(); // 切换为写模式
            }

        } catch (IOException e) {
        }


    }
}
